//
//  CFriendListView.m
//  HCHK_iphone
//
//  Created by yilong zhang on 12-1-2.
//  Copyright 2012年 __MyCompanyName__. All rights reserved.
//

#import "CFriendListView.h"

//========================================================================================================================

@implementation CFrdItemView

@synthesize m_Icon;
@synthesize m_Nick;
@synthesize m_City;
@synthesize m_FrdNum;
@synthesize m_PdtNum;
@synthesize m_DisNum;

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        
        m_Icon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
        m_Icon.backgroundColor = [UIColor clearColor];
        [self addSubview:m_Icon];
        [m_Icon release];
        
        UIFont *font = [UIFont fontWithName:@"Helvetica" size:15];
        
        m_Nick = [[UILabel alloc] initWithFrame:CGRectMake(52, 0, 100, 25)];
        m_Nick.font = font;
        m_Nick.text = @"昵称";
        m_Nick.backgroundColor = [UIColor clearColor];
        [self addSubview:m_Nick];
        [m_Nick release];
        
        m_City = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width-140, 0, 117, 25)];
        m_City.font = font;
        m_City.text = @"城市";
        m_City.textAlignment = UITextAlignmentRight;
        m_City.backgroundColor = [UIColor clearColor];
        [self addSubview:m_City];
        [m_City release];
        
        font = [UIFont fontWithName:@"Helvetica" size:13];
        
        m_FrdNum = [[UILabel alloc] initWithFrame:CGRectMake(52, 30, 70, 20)];
        m_FrdNum.textAlignment = UITextAlignmentCenter;
        m_FrdNum.text = @"好友(0)";
        m_FrdNum.font = font;
        m_FrdNum.backgroundColor = [UIColor clearColor];
        m_FrdNum.textColor = [UIColor darkGrayColor];
        [self addSubview:m_FrdNum];
        [m_FrdNum release];
        
        m_PdtNum = [[UILabel alloc] initWithFrame:CGRectMake(129, 30, 70, 20)];
        m_PdtNum.textAlignment = UITextAlignmentCenter;
        m_PdtNum.text = @"美食(0)";
        m_PdtNum.font = font;
        m_PdtNum.backgroundColor = [UIColor clearColor];
        m_PdtNum.textColor = [UIColor darkGrayColor];
        [self addSubview:m_PdtNum];
        [m_PdtNum release];
        
        m_DisNum = [[UILabel alloc] initWithFrame:CGRectMake(206, 30, 70, 20)];
        m_DisNum.textAlignment = UITextAlignmentCenter;
        m_DisNum.text = @"评论(0)";
        m_DisNum.font = font;
        m_DisNum.backgroundColor = [UIColor clearColor];
        m_DisNum.textColor = [UIColor darkGrayColor];
        [self addSubview:m_DisNum];
        [m_DisNum release];
        
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 53, frame.size.width, 1)];
        line.image = [UIImage imageNamed:@"line.png"];
        [self addSubview:line];
        [line release];
    }
    
    return self;
}


@end

//========================================================================================================================

@implementation UITableViewCellEx

@synthesize m_InfoView;

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier  Size:(CGSize)size
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        
        m_InfoView = [[CFrdItemView alloc] initWithFrame:CGRectMake(0, 10, size.width, size.height)];
        [self addSubview:m_InfoView];
        [m_InfoView release];
    }
    
    return self;
}

@end


//========================================================================================================================

@implementation CFriendListView

@synthesize delegate;
@synthesize m_SearchView;
@synthesize m_Scroll;
@synthesize m_TableView;
@synthesize m_Cell;
@synthesize m_Frds;
@synthesize m_UserID;
@synthesize m_bIsLoading;
@synthesize m_bIsPageEnd;
@synthesize m_NativeCnt;
@synthesize m_NetCnt;
@synthesize m_Task;
@synthesize m_FootView;
@synthesize m_LoadView;
@synthesize m_NoData;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // Initialization code
        self.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0];
        self.m_bIsLoading = NO;
        self.m_bIsPageEnd = NO;
        self.m_Cell = nil;
        self.m_UserID = -1;
        self.m_Frds = [NSMutableArray array];
        
        m_NetCnt = [[CAscCounter alloc] init];
        m_NetCnt.m_nLimit = 6;
        m_NetCnt.m_nOffset= 0;
        m_NativeCnt = [[CAscCounter alloc] init];
        m_NativeCnt.m_nLimit = 6;
        m_NativeCnt.m_nOffset= 0;
        
        [self AddSearchView];
        
        //footview
        m_FootView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 50)];
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        indicator.alpha = 0.0;
        indicator.frame = CGRectMake(0, 0, 25, 25);
        indicator.center= CGPointMake(m_FootView.frame.size.width/2, m_FootView.frame.size.height/2);
        [m_FootView addSubview:indicator];
        [indicator release];
        
        //scrollview
        m_Scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, m_SearchView.frame.size.height, self.frame.size.width, self.frame.size.height-m_SearchView.frame.size.height)];
        m_Scroll.backgroundColor = [UIColor clearColor];
        m_Scroll.delegate = self;
        m_Scroll.contentSize = CGSizeMake(m_Scroll.contentSize.width, self.frame.size.height-m_SearchView.frame.size.height+m_FootView.frame.size.height);
        [self addSubview:m_Scroll];
        [m_Scroll release];
        
        //tableview
        m_TableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 0)];
        m_TableView.backgroundColor = [UIColor clearColor];
        m_TableView.scrollEnabled = NO;
        m_TableView.delegate = self;
        m_TableView.dataSource=self;
        [m_Scroll addSubview:m_TableView];
        [m_TableView release];
        
        //footview
        [m_Scroll addSubview:m_FootView];
        [m_FootView release];
        
        [self SetUpLoadView];
        
        //nodata
        m_NoData = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width-140, 40)];
        m_NoData.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
        m_NoData.backgroundColor = [UIColor clearColor];
        m_NoData.font = [UIFont systemFontOfSize:16];
        m_NoData.numberOfLines = 2;
        m_NoData.lineBreakMode = UILineBreakModeWordWrap;
        m_NoData.alpha = 0.0;
        m_NoData.text  = @"嗨!你还没有关注的对象,赶快查找添加吧.";
        [self addSubview:m_NoData];
        [m_NoData release];
    }
    
    return self;
}

-(void)dealloc
{
    [m_Frds release];
    [m_FootView release];
    
    [super dealloc];
}

//loadview
-(void)SetUpLoadView
{
    m_LoadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    m_LoadView.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    m_LoadView.alpha  = 0.0;
    [self addSubview:m_LoadView];
    [m_LoadView release];
    
    UIView *back = [[UIView alloc] initWithFrame:CGRectMake(0, 0, m_LoadView.frame.size.width, m_LoadView.frame.size.height)];
    back.backgroundColor = [UIColor blackColor];
    back.layer.cornerRadius = 5;
    back.alpha = 0.8;
    [m_LoadView addSubview:back];
    [back release];
        
    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    indicator.frame = CGRectMake(0, 0, 25, 25);
    indicator.center= CGPointMake(m_LoadView.frame.size.width/2, m_LoadView.frame.size.height/2);
    [m_LoadView addSubview:indicator];
    [indicator release];
}

-(void)ShowLoadView
{
    [[[m_LoadView subviews] objectAtIndex:1] startAnimating];
    m_LoadView.alpha = 1.0;
}

-(void)HiddenLoadView
{
    m_LoadView.alpha = 0.0;
    [[[m_LoadView subviews] objectAtIndex:1] stopAnimating];
}

//footview
-(void)ShowFootView
{
    UIActivityIndicatorView *indicator = [[m_FootView subviews] objectAtIndex:0];
    [indicator startAnimating];
    indicator.alpha = 1.0;
}

-(void)HiddenFootView
{
    UIActivityIndicatorView *indicator = [[m_FootView subviews] objectAtIndex:0];
    indicator.alpha = 0.0;
    [indicator stopAnimating];
}

//searchview
-(void)AddSearchView
{
    if (!m_SearchView)
    {
        m_SearchView = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 44)];
        m_SearchView.backgroundColor = [UIColor clearColor];
        m_SearchView.delegate = self;
        [self addSubview:m_SearchView];
        [m_SearchView release];
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, m_SearchView.frame.size.width, m_SearchView.frame.size.height)];
        view.backgroundColor = self.backgroundColor;
        [m_SearchView insertSubview:view atIndex:[[m_SearchView subviews] count]-1];
        [view release];
    }
}

-(void)CommitSearchRequest
{
    //
}

-(void)ReceiveSearchResponse:(NSDictionary*)data
{
    //
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [m_SearchView resignFirstResponder];
    
    [self ShowLoadView];
    int nCnt = 0;
    for (CFriend *friend in m_Frds)
    {
        if ([friend.F_Nick isEqualToString:searchBar.text])
        {
            m_Cell.selected = NO;
            NSIndexPath *path = [NSIndexPath indexPathForRow:nCnt inSection:0];
            m_Cell = (UITableViewCellEx*)[m_TableView cellForRowAtIndexPath:path];
            m_Cell.selected = YES;
            [m_TableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
            break;
        }
        
        ++nCnt;
    }
    [self HiddenLoadView];
}

-(void)SetFrdLstViewInfo
{
    CUser *user = [CUser DefaultUser];
    m_UserID = [user.U_AID longValue];
    
    [self ShowLoadView];
    if (1 == [self GetUsersFriends])
    {
        [self HiddenLoadView];
    }
}

-(void)ClearData
{
    m_UserID = -1;
    [m_Frds removeAllObjects];
    
    m_TableView.frame = CGRectMake(m_TableView.frame.origin.x, m_TableView.frame.origin.y, m_TableView.frame.size.width, 0);
    m_FootView.frame  = CGRectMake(m_FootView.frame.origin.x, m_TableView.frame.size.height, m_FootView.frame.size.width, m_FootView.frame.size.height);
    m_Scroll.contentSize = CGSizeMake(m_Scroll.contentSize.width, self.frame.size.height-m_SearchView.frame.size.height+m_FootView.frame.size.height);
    [m_Scroll setContentOffset:CGPointMake(0, 0)];
    
    [m_TableView reloadData];
    m_SearchView.text     = nil;
    m_NetCnt.m_nLimit     = 6;
    m_NetCnt.m_nOffset    = 0;
    m_NativeCnt.m_nOffset = 0;
    m_NativeCnt.m_nLimit  = 6;
    [[CDownLoadManager DefaultDownLoadManager] CancelTask:m_Task];
    self.m_Task = nil;
    m_bIsLoading= NO;
    m_bIsPageEnd= NO;
    m_Cell = nil;
    m_NoData.alpha=0.0;
    [self HiddenLoadView];
    [self HiddenFootView];
}

-(int)GetUsersFriends
{
    if (!m_bIsLoading)
    {
        m_bIsLoading = YES;
        
        //首先从本地获取好友数据
        NSArray *Rets = [self GetNativeFriend:m_NativeCnt.m_nOffset Limit:m_NativeCnt.m_nLimit Table:[NSString stringWithFormat:@"%@_friend", [CUser DefaultUser].U_Name]];
        if (Rets && [Rets count] > 0)
        {
            [self AddFriendsToList:Rets];
            m_NativeCnt.m_nOffset += [Rets count];
            m_bIsLoading = NO;
            return 1;
        }
        //本地没有好友数据向服务器获取
        else 
        {
            m_NativeCnt.m_nLimit = 0;
            //Get friends from server
            m_NetCnt.m_nOffset = [m_Frds count];
            [self CommitMyFriendsRequest:m_NetCnt.m_nOffset Limit:m_NetCnt.m_nLimit Action:OP_GETMYFRIENDS];
            return 0;
        }
    }
    
    return 1;
}

-(void)AddNetFriendsToList:(NSArray*)friends
{
    CGFloat fheight = [friends count]*65;
    m_TableView.frame= CGRectMake(m_TableView.frame.origin.x, m_TableView.frame.origin.y, m_TableView.frame.size.width, m_TableView.frame.size.height+fheight);
    m_FootView.frame = CGRectMake(m_FootView.frame.origin.x, m_TableView.frame.size.height, m_FootView.frame.size.width, m_FootView.frame.size.height);
    fheight = m_TableView.frame.size.height+m_FootView.frame.size.height;
    if (fheight > m_Scroll.frame.size.height+m_FootView.frame.size.height)
        m_Scroll.contentSize = CGSizeMake(m_Scroll.contentSize.width, m_TableView.frame.size.height+m_FootView.frame.size.height);
    
    CFriend *friend = nil;
    for (NSDictionary *data in friends)
    {
        friend = [[CFriend alloc] init];
        [friend SetFriendWithDic:data];
        if (0 == [friend SaveFriend:[CUser DefaultUser].m_FriendTable])
        {
            [m_Frds addObject:friend];
        }
        [friend release];
    }
    
    [m_TableView reloadData];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [m_SearchView resignFirstResponder];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [m_SearchView resignFirstResponder];
    
    //more
    if ((scrollView.contentOffset.y+scrollView.frame.size.height) - scrollView.contentSize.height > 50 && !m_bIsLoading)
    {
        [self ShowFootView];
        m_bIsPageEnd = YES;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (!m_bIsLoading && m_bIsPageEnd)
    {
        if ([self GetUsersFriends])
        {
            [self HiddenFootView];
        }
    }
}

//tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [m_Frds count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65.0;
}
/*
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 45;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (!m_FootView)
    {
        m_FootView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 45)];
        
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        indicator.hidden = YES;
        indicator.frame = CGRectMake(0, 0, 25, 25);
        indicator.center= CGPointMake(m_FootView.frame.size.width/2, m_FootView.frame.size.height/2);
        [m_FootView addSubview:indicator];
        [indicator release];
    }
    
    return m_FootView;
}
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCellStyle style = UITableViewCellStyleValue1;
	
	UITableViewCellEx *cell = (UITableViewCellEx*)[tableView dequeueReusableCellWithIdentifier:@"BaseCell"];
	
	if (nil == cell)
	{
		cell = [[[UITableViewCellEx alloc] initWithStyle:style reuseIdentifier:@"BaseCell" Size:CGSizeMake(self.frame.size.width-20, 65)] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        //cell.selectionStyle= UITableViewCellSelectionStyleNone;
    }
    
    NSData *data = nil;
    UIImage*image= nil;
    CFriend *friend = [m_Frds objectAtIndex:indexPath.row];
    friend.m_FIconView = cell.m_InfoView.m_Icon;
    data = [friend GetFriendIcon];
    if (data)
    {
        image = [UIImage imageWithData:data];
        friend.m_FIconView.image = image;
    }
    else 
    {
        image = [CMainPageCtrl DefaultMainPageCtrl].m_DfIcon;
    }
    cell.m_InfoView.m_Icon.image = image;
    cell.m_InfoView.m_Nick.text  = friend.F_Nick;
    cell.m_InfoView.m_City.text  = friend.F_City;
    cell.m_InfoView.m_FrdNum.text= [NSString stringWithFormat:@"美食(%ld)", [friend.F_Attent longValue]];
    cell.m_InfoView.m_PdtNum.text= [NSString stringWithFormat:@"评论(%ld)", [friend.F_Attented longValue]];
    cell.m_InfoView.m_DisNum.text= [NSString stringWithFormat:@"好友(%ld)", [friend.F_Pub longValue]];
    
    return cell;
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    m_Cell.selected = NO;
    m_Cell = (UITableViewCellEx*)[m_TableView cellForRowAtIndexPath:indexPath];
    
    return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [m_SearchView resignFirstResponder];
    
    [delegate DidFriendListSelected:[m_Frds objectAtIndex:indexPath.row]];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [m_SearchView resignFirstResponder];
}

-(void)AddFriendsToList:(NSArray*)friends
{
    NSArray        *data= nil;
    CFriend     *friend = nil;
    
    CGFloat fheight = [friends count]*65;
    m_TableView.frame= CGRectMake(m_TableView.frame.origin.x, m_TableView.frame.origin.y, m_TableView.frame.size.width, m_TableView.frame.size.height+fheight);
    m_FootView.frame = CGRectMake(m_FootView.frame.origin.x, m_TableView.frame.size.height, m_FootView.frame.size.width, m_FootView.frame.size.height);
    fheight = m_TableView.frame.size.height+m_FootView.frame.size.height;
    if (fheight > m_Scroll.frame.size.height+m_FootView.frame.size.height)
        m_Scroll.contentSize = CGSizeMake(m_Scroll.contentSize.width, m_TableView.frame.size.height+m_FootView.frame.size.height);
    
    for (int i=0; i < [friends count]; i++)
    {
        data = [friends objectAtIndex:i];
        friend = [[CFriend alloc] init];
        [friend SetFriendWithArr:data];
        [m_Frds addObject:friend];
        [friend release];
    }
    
    [m_TableView reloadData];
}

-(NSArray*)GetNativeFriend:(int)offset Limit:(int)limit Table:(NSString*)table
{
    NSArray *results = nil;
    
    if (m_NativeCnt.m_nLimit > 0)
    {
        results = [CFriend GetFriends:table Where:nil Offset:m_NativeCnt.m_nOffset Limit:m_NativeCnt.m_nLimit];
    }
    
    return results;
}

//request
-(void)CommitMyFriendsRequest:(int)offset Limit:(int)limit Action:(NSString*)action
{
    CUser *user = [CUser DefaultUser];
    
    NSLog(@"\r\n\r\n获得%@的好友开始\r\n\r\n", user.U_Name);
    
    NSMutableString *des = [NSMutableString stringWithCapacity:6];
    
    [des appendFormat:@"clientID=%@", [AppConfig DefaultAppConfig].m_strUDID];
    [des appendFormat:@"&mobikey=%@", user.U_Token];
    [des appendFormat:@"&sessionid=%@", user.U_Session];
    [des appendFormat:@"&action=%@", action];
    [des appendFormat:@"&cursor=%d", offset];
    [des appendFormat:@"&offset=%d", limit];
    
    NSLog(@"\r\n\r\n获得好友请求:%@\r\n\r\n", des);
    
    self.m_Task = [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_MYFRIEND Sponsor:self PostData:[des dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithLong:m_UserID] MType:Post UserInfo:nil];
    
    NSLog(@"\r\n\r\n获得%@的好友结束", user.U_Name);
}

-(void)DidOperationFinished:(COperation*)op Data:(NSData*)data Other:(id)other UserInfo:(id)userinfo
{
    NSString      *json = nil;
    NSDictionary  *dic  = nil;
    NSArray       *items= nil;
    int            nCode= -1;
    
    if (m_UserID == [other longValue])
    {
        json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        dic  = [json JSONValue];
        NSLog(@"\r\n\r\n收到的好友的原始数据:%@\r\n\r\n",json);
        
        nCode = [[dic objectForKey:@"Msg_error"] intValue];
        
        if (0 == nCode && dic)
        {
            if (m_UserID == [[CUser DefaultUser].U_AID longValue])
            {
                m_NetCnt.m_nTotal = [[dic objectForKey:@"total"] intValue];
                items = [dic objectForKey:@"Resource"];
                [self AddNetFriendsToList:items];
                [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[items count]];
            }
        } 
        else 
        {
            //json error alterview
            //NSLog(@"\r\n\r\n获得好友错误,不能正确解析json.\r\n\r\n");
        }
        
        [json release];
    }
    
    self.m_Task = nil;
    m_bIsLoading= NO;
    m_bIsPageEnd= NO;
    [self HiddenLoadView];
    [self HiddenFootView];
    
    if (0 == [m_Frds count])
        m_NoData.alpha = 1.0;
}

-(void)DidOperationError:(COperation*)op Error:(NSError*)error Other:(id)other UserInfo:(id)userinfo
{
    self.m_Task = nil;
    m_bIsPageEnd= NO;
    m_bIsLoading= NO;
    [self HiddenLoadView];
    [self HiddenFootView];
    
    if (0 == [m_Frds count])
        m_NoData.alpha = 1.0;
}

-(void)DidOperationTimeOut:(COperation*)op Other:(id)other
{
    self.m_Task = nil;
    m_bIsPageEnd= NO;
    m_bIsLoading= NO;
    [self HiddenLoadView];
    [self HiddenFootView];
    
    if (0 == [m_Frds count])
        m_NoData.alpha = 1.0;
}

@end
